<?php

namespace app\controller;

use think\Request;
use think\facade\Db;
use think\response\Json;

class Notice
{
    /**
     * 获取公告列表（管理端）
     */
    public function getList(Request $request): Json
    {
        try {
            $pageNo = $request->param('pageNo', 1);
            $pageSize = $request->param('pageSize', 10);
            $title = $request->param('title', '');
            $category = $request->param('category', '');
            $status = $request->param('status', '');
            
            $where = [];
            
            if (!empty($title)) {
                $where[] = ['title', 'like', '%' . $title . '%'];
            }
            
            if (!empty($category)) {
                $where['category'] = $category;
            }
            
            if ($status !== '') {
                $where['status'] = $status;
            }
            
            $list = Db::name('notice')
                ->where($where)
                ->order('create_time desc')
                ->page($pageNo, $pageSize)
                ->select();
            
            $total = Db::name('notice')
                ->where($where)
                ->count();
            
            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => [
                    'list' => $list,
                    'total' => $total
                ]
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => '获取公告列表失败：' . $e->getMessage(),
                'data' => null
            ]);
        }
    }

    /**
     * 获取公告列表（前端展示）
     */
    public function getPublicList(Request $request): Json
    {
        try {
            $page = $request->param('page', 1);
            $limit = $request->param('limit', 10);
            $category = $request->param('category', '');
            
            $where = ['status' => 1]; // 只显示已发布的公告
            
            if (!empty($category)) {
                $where['category'] = $category;
            }
            
            $list = Db::name('notice')
                ->where($where)
                ->order('publish_time desc')
                ->page($page, $limit)
                ->select();
            
            $total = Db::name('notice')
                ->where($where)
                ->count();
            
            // 处理数据格式
            foreach ($list as &$item) {
                $item['summary'] = mb_substr(strip_tags($item['content']), 0, 100) . '...';
                $item['createTime'] = date('Y-m-d', strtotime($item['publish_time']));
                $item['categoryClass'] = $this->getCategoryClass($item['category']);
            }
            
            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => [
                    'list' => $list,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit
                ]
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => '获取公告列表失败：' . $e->getMessage(),
                'data' => null
            ]);
        }
    }
    
    /**
     * 获取公告详情
     */
    public function getDetail(Request $request): Json
    {
        try {
            $id = $request->param('id');
            
            if (empty($id)) {
                return json([
                    'code' => 400,
                    'msg' => '公告ID不能为空',
                    'data' => null
                ]);
            }
            
            $notice = Db::name('notice')
                ->where(['id' => $id, 'status' => 1])
                ->find();
            
            if (empty($notice)) {
                return json([
                    'code' => 404,
                    'msg' => '公告不存在或已下线',
                    'data' => null
                ]);
            }
            
            // 格式化数据
            $notice['createTime'] = $notice['publish_time'];
            $notice['categoryClass'] = $this->getCategoryClass($notice['category']);
            $notice['views'] = rand(50, 200); // 模拟浏览量
            
            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => $notice
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => '获取公告详情失败：' . $e->getMessage(),
                'data' => null
            ]);
        }
    }
    
    /**
     * 获取公告分类列表
     */
    public function getCategories(): Json
    {
        try {
            $categories = Db::name('notice')
                ->where('status', 1)
                ->group('category')
                ->column('category');
            
            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => $categories
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => '获取分类失败：' . $e->getMessage(),
                'data' => []
            ]);
        }
    }
    
    /**
     * 保存公告（新增/编辑）
     */
    public function save(Request $request): Json
    {
        try {
            $data = $request->param();
            
            // 验证必填字段
            if (empty($data['title'])) {
                return json([
                    'code' => 0,
                    'msg' => '公告标题不能为空',
                    'data' => null
                ]);
            }
            
            if (empty($data['content'])) {
                return json([
                    'code' => 0,
                    'msg' => '公告内容不能为空',
                    'data' => null
                ]);
            }
            
            if (empty($data['category'])) {
                return json([
                    'code' => 0,
                    'msg' => '公告类型不能为空',
                    'data' => null
                ]);
            }
            
            if (empty($data['publish_time'])) {
                return json([
                    'code' => 0,
                    'msg' => '发布时间不能为空',
                    'data' => null
                ]);
            }
            
            $saveData = [
                'title' => $data['title'],
                'content' => $data['content'],
                'category' => $data['category'],
                'publish_time' => $data['publish_time'],
                'status' => $data['status'] ?? 1,
            ];
            
            if (!empty($data['id'])) {
                // 编辑
                $saveData['update_time'] = date('Y-m-d H:i:s');
                $result = Db::name('notice')->where('id', $data['id'])->update($saveData);
                $message = '公告更新成功';
                $noticeId = $data['id'];
            } else {
                // 新增
                $saveData['create_time'] = date('Y-m-d H:i:s');
                $noticeId = Db::name('notice')->insertGetId($saveData);
                $result = $noticeId > 0;
                $message = '公告发布成功';
            }
            
            if ($result) {
                return json([
                    'code' => 1,
                    'msg' => $message,
                    'data' => ['id' => $noticeId]
                ]);
            } else {
                return json([
                    'code' => 0,
                    'msg' => '操作失败',
                    'data' => null
                ]);
            }
            
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => '操作失败：' . $e->getMessage(),
                'data' => null
            ]);
        }
    }
    
    /**
     * 删除公告
     */
    public function delete(Request $request): Json
    {
        try {
            $ids = $request->param('ids');
            
            if (empty($ids)) {
                return json([
                    'code' => 0,
                    'msg' => '请选择要删除的公告',
                    'data' => null
                ]);
            }
            
            // 支持批量删除
            if (is_string($ids)) {
                $ids = explode(',', $ids);
            }
            
            $result = Db::name('notice')->where('id', 'in', $ids)->delete();
            
            if ($result) {
                return json([
                    'code' => 1,
                    'msg' => '删除成功',
                    'data' => null
                ]);
            } else {
                return json([
                    'code' => 0,
                    'msg' => '删除失败',
                    'data' => null
                ]);
            }
            
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => '删除失败：' . $e->getMessage(),
                'data' => null
            ]);
        }
    }

    /**
     * 获取分类样式类名
     */
    private function getCategoryClass($category): string
    {
        $categoryMap = [
            '公司公告' => 'category-system',
            '重要通知' => 'category-normal',
            '流程通知' => 'category-process'
        ];
        
        return $categoryMap[$category] ?? 'category-normal';
    }
}
